namespace Maple.Branch.Identity.Exceptions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using Extensions;
    using JetBrains.Annotations;
    using Localizations;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.Extensions.Localization;
    using Volo.Abp;
    using Volo.Abp.ExceptionHandling;
    using Volo.Abp.Localization;

    [Serializable]
    public class IdentityResultException : BusinessException, ILocalizeErrorMessage
    {
        public IdentityResult IdentityResult { get; }

        public IdentityResultException([NotNull] IdentityResult identityResult)
            : base(
                code: $"Identity.{identityResult.Errors.First().Code}",
                message: identityResult.Errors.Select(err => err.Description).JoinAsString(", "))
        {
            IdentityResult = Check.NotNull(identityResult, nameof(identityResult));
        }

        public IdentityResultException(SerializationInfo serializationInfo, StreamingContext context)
            : base(serializationInfo, context)
        {
        }

        public virtual string LocalizeMessage(LocalizationContext context)
        {
            return IdentityResult.LocalizeErrors(context.LocalizerFactory.Create<IdentityLocalResource>());
        }
    }
}
